package com.study.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.entity.common.CommonRequestEntity;
import com.study.entity.common.CommonResponseEntity;
import com.study.entity.db3.Role;
import com.study.entity.db3.vo.RoleVO;
import com.study.enumeration.ResponseEnum;
import com.study.exception.DefinitionException;
import com.study.service.db3.IResourceService;
import com.study.service.db3.IRoleService;
import com.study.util.ResponseUtil;
import com.study.util.treeutil.TreeNodeMap;

/**
 * 角色表 前端控制器
 * 
 * @author chenk
 *
 */
@Controller
@RequestMapping("/role")
public class RoleController {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IResourceService resourceService;

	/**
	 * 进入列表页面
	 * 
	 * @return
	 */
	@GetMapping("/toList")
	public String toList() {
		return "role/roleList";
	}

	/**
	 * 查询列表
	 * 
	 * @param requestEntity
	 * @return
	 */
	@GetMapping("/list")
	@ResponseBody
	public CommonResponseEntity<Map<String, Object>> list(CommonRequestEntity requestEntity) {
		PageHelper.startPage(requestEntity.getPage(), requestEntity.getLimit());
		Page<Role> roles = roleService.queryPage(requestEntity.getRequestParams());
		return ResponseUtil.buildPage(roles);
	}

	/**
	 * 进入新增页
	 * 
	 * @return
	 */
	@GetMapping("toAdd")
	public String toAdd() {
		return "role/roleAdd";
	}

	/**
	 * 资源树形结构
	 * 
	 * @param roleId 角色id
	 * @param flag   flag=0 编辑； flag=1 详情
	 * @return
	 */
	@GetMapping({ "listResource", "listResource/{roleId}", "listResource/{roleId}/{flag}" })
	@ResponseBody
	public CommonResponseEntity<List<TreeNodeMap>> listResource(@PathVariable(required = false) Long roleId,
			@PathVariable(required = false) Integer flag) {
		List<TreeNodeMap> listResource = resourceService.listResource(Arrays.asList(roleId), flag);
		LOGGER.info("树形数据：" + listResource);
		return ResponseUtil.success(listResource);
	}

	/**
	 * 新增角色
	 * 
	 * @param role
	 * @return
	 */
	@PostMapping
	@ResponseBody
	public CommonResponseEntity<Object> add(@RequestBody Role role) {
		try {
			roleService.saveRole(role);
			return ResponseUtil.success();
		} catch (Exception e) {
			LOGGER.error("保存失败：" + e.getMessage());
			throw new DefinitionException(ResponseEnum.OPR_FAIL);
		}
	}

	/**
	 * 删除角色
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ResponseBody
	public CommonResponseEntity<Object> delete(@PathVariable Long id) {
		try {
			roleService.deleteById(id);
			return ResponseUtil.success();
		} catch (Exception e) {
			if (e instanceof DefinitionException) {
				DefinitionException e1 = (DefinitionException) e;
				LOGGER.error("删除失败：" + e1.getErrorMsg());
				throw new DefinitionException(e1.getErrorCode(), e1.getErrorMsg());
			}
			LOGGER.error("删除失败：" + e.getMessage());
			throw new DefinitionException(ResponseEnum.OPR_FAIL);
		}
	}

	/**
	 * 进入更新页
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("toUpdate/{id}")
	public String toUpdate(@PathVariable Long id, Model model) {
		Role role = roleService.getById(id);
		model.addAttribute("role", role);
		return "role/roleUpdate";
	}

	/**
	 * 修改
	 * 
	 * @param role
	 * @return
	 */
	@PutMapping
	@ResponseBody
	public CommonResponseEntity<Object> updateSubmit(@RequestBody Role role) {
		try {
			roleService.updateRole(role);
			return ResponseUtil.success();
		} catch (Exception e) {
			LOGGER.error("保存失败：" + e.getMessage());
			throw new DefinitionException(ResponseEnum.OPR_FAIL);
		}
	}

	/**
	 * 进入详情页
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("toDetail/{id}")
	public String toDetail(@PathVariable Long id, Model model) {
		Role role = roleService.getById(id);
		model.addAttribute("role", role);
		return "role/roleDetail";
	}

	/**
	 * 账户新增、修改时，角色下拉选项
	 * 
	 * @param accountId
	 * @return
	 */
	@GetMapping({ "/queryRolesForSelect", "/queryRolesForSelect/{accountId}" })
	@ResponseBody
	public CommonResponseEntity<List<RoleVO>> queryRolesForSelect(@PathVariable(required = false) Long accountId) {
		List<RoleVO> list = roleService.queryRolesForSelect(accountId);
		return ResponseUtil.success(list);
	}
}
